# Create your views here.
# !/usr/bin/python
# -*- coding: utf-8 -*-

__author__ = 'george lin'

from django.conf import settings
from utils.signUtils import signutils
from utils.log_util import get_logger
from utils.http_util import api_request
from utils.time_util import utc_to_local
from django.http.response import HttpResponse
import uuid
import logging
import time
import json

logger = get_logger()

def send_message(request):
    msg_list = parse(json.loads(request.body))
    if msg_list:
        params = {
            "timestamp": int(round(time.time() * 1000)),
            "systemCode": settings.SYSTEMCODE,
            "messageType": 4,
            "messageCodeDTOList": msg_list,
            "appKey": settings.APPKEY,
            "notifyUrl": settings.NOTIFYURL
        }
        sign = signutils(appSecret=settings.APPSECRET, params=params)
        params['sign'] = sign
        logger.info(params)
        headers={
            'Content-Type': 'application/json'
        }
        result = api_request(method="POST", url=settings.SERVERURL, params=params, headers=headers)
        logger.info(result)
        if result:
            return HttpResponse("{'success': False, 'obj': None, 'msg': '服务器内部错误', 'status_code': 200}", content_type='application/json')
        else:
           return HttpResponse("{'success': False, 'obj': None, 'msg': '服务器内部错误', 'status_code': 500}", content_type='application/json')


def parse_alertmanage_msg(params):
    """
    解析alertmanager告警短信,返回一个告警/恢复信息列表
    """
    if not isinstance(params, dict):
        logger.error("request params must be dict, not {0}".format(type(params)))
        return None
    else:
        message_list = []
        logger.info(json.dumps(params,indent=4))
        for info in params.get("alerts"):
            if info["status"] == "firing":
                start_time = utc_to_local(info.get("startsAt", None))
                content =  settings.FIRINGMSG.format(alertname=info["labels"].get("alertname", None),
                                            summary=info["annotations"].get("summary", None),
                                            status=info["labels"].get("severity", None),
                                            hosts=info["labels"].get("hosts", None),
                                            instance=info["labels"].get("instance", None),
                                            startsAt=start_time,
                                            app=info["labels"].get("app", None),
                                            description=info["annotations"].get("description", None))
            else:
                start_time = utc_to_local(info.get("startsAt", None))
                end_time = utc_to_local(info.get("endsAt", None))
                content = settings.RESOLVEMSG.format(alertname=info["labels"].get("alertname", None),
                                            summary=info["annotations"].get("summary", None),
                                            hosts=info["labels"].get("hosts", None),
                                            instance=info["labels"].get("instance", None),
                                            startsAt=start_time,
                                            endsAt=end_time,
                                            app=info["labels"].get("app", None))
            for i in range(0, len(settings.PHONENUMS)):
                message = {
                    "messageId": str(uuid.uuid4()).replace("-", ""),
                    "phoneNumber": settings.PHONENUMS[i],
                    "content": content
                }
                message_list.append(message)
        return message_list